package com.eb.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

/**
 * 签名串工具类
 * @author Administrator
 *
 */
public class SignUtil {
	
	private static Logger logger = Logger.getLogger(SignUtil.class);
	
	private static final String SIGN_KEY = "";
	
	private static final String TOKEN = "token";
	
	private static final String LOGIN_TOKEN = "";
	
	
	/**
	 * map:验签的参数Map
	 * 2016-6-21
	 * v-haowang
	 */
	public static boolean verifySignature(Map<String,String> paramMap){
		String reqToken = getStr(paramMap.get(TOKEN));
		if("".equals(reqToken)){
			return false;
		}
		paramMap.remove(TOKEN);
		paramMap.remove(LOGIN_TOKEN);
		String sign = getSign(paramMap, SIGN_KEY);
		if(!sign.equals(reqToken)){
			return false;
		}
		return true;
	}
	
	/**
	 * map:验证登录状态
	 * 2016-6-21
	 * v-haowang
	 * verifyLogin：是否验证登录
	 */
	public static boolean verifyLogin(String reqLoginTOken,String localLoginToken){
		if("".equals(getStr(localLoginToken)) || "".equals(getStr(reqLoginTOken)))
			return false;
		if(!reqLoginTOken.equals(getStr(localLoginToken)))
			return false;
		return true;
	}
	
	/**
	 * 得到签名串
	 * 2016-6-21
	 * v-haowang
	 */
	public static String getSign(Map<String,String> map,String key){
		String sign = "";
		try {
			List<String> list = new ArrayList<String>();
			for(Map.Entry<String,String> entry:map.entrySet()){
			    if(!"".equals(getStr(entry.getValue()))){
			        list.add(entry.getKey() + "=" + entry.getValue().trim() + "&");
			    }
			}
			int size = list.size();
			String [] arrayToSort = list.toArray(new String[size]);
			Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
			StringBuilder sb = new StringBuilder();
			for(int i = 0; i < size; i ++) {
			    sb.append(arrayToSort[i]);
			}
			sb.append("key="+key);
			sign = EncryptUtil.MD5(sb.toString()).toUpperCase();
		} catch (Exception e) {
			logger.error("生成签名串失败", e);
		}
		return sign;
	}
	
	/**
	 * 
	 * 2016-7-6
	 * v-haowang
	 * 得到loginToken加密串
	 * @throws Exception 
	 */
	public static String getLoginToken(String userid,String pwd) throws Exception{
		return EncryptUtil.MD5(userid+"_"+pwd);
	}
	
	/**
	 * 判断空值
	 * 2016-6-21
	 * v-haowang
	 */
	public static String getStr(String s){
		if(s == null){
			return "";
		}
		return s;
	}
}
